<template>
    <div>
        <el-upload
            class="avatar-uploader"
            :action="uploadApi"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="header"
        >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
</template>

<script>
export default {
    name: "ImgUpload",
    props: ["size", "urlTemp"],
    data() {
        return { 
            imageUrl: "",
            uploadApi: "http://ycwback.0melon0.cn/api/img/uploadImg",
            //  uploadApi: "http://localhost:8000/api/img/uploadImg",
            header: {
                "token": "bearer "+localStorage.getItem("token")
            }
        };
    },

    watch: {
        urlTemp: function(val) {
            this.imageUrl = val;
 
        }
    },
    methods: {
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
            console.log(res);
            console.log(file);
            if (res.status == 2) {
                // this.OldImageUrl = this.updateForm.avatar_url;
                // this.updateForm.avatar_url = res.path;
                this.$emit("uploaded", res);
            } else {
                this.$emit("uploadFail", res);
            }
        },
        beforeAvatarUpload(file) {
            const isJPG =
                file.type === "image/jpeg" || file.type === "image/png";
            const isLt = file.size / 1024 < this.size;

            if (!isJPG) {
                this.$message.error("上传头像图片只能是 JPG 或 png 格式!");
            }
            if (!isLt) {
                this.$message.error(`上传头像图片大小不能超过 ${this.size}kb!`);
            }
            return isJPG && isLt;
        }
    }
};
</script>

<style lang="scss" sccoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>